package com.es.esjest.esservice;

import com.es.esjest.pojo.SearchParam;
import com.es.esjest.pojo.User;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author luheng
 * @create 2019/6/28
 */
@Service
public class EsService {

    private final static Logger logger= LoggerFactory.getLogger(EsService.class);
    @Autowired
    private JestClient jestClient;

    public String search(SearchParam param) {
        logger.info("es查询参数 param {}", param);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //设置分页
        if (param.getPageNo() > 0 && param.getPageSize() > 0) {
            searchSourceBuilder.from((param.getPageNo() - 1) * param.getPageSize());
            searchSourceBuilder.size(param.getPageSize());
        }

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getAdress())) {
            boolQueryBuilder.must(QueryBuilders.fuzzyQuery(User.Property.adress, param.getAdress()));
        }
        if (!StringUtils.isEmpty(param.getInterests())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery(User.Property.interests, param.getInterests()));
        }
        if (!StringUtils.isEmpty(param.getAge())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery(User.Property.age);
            rangeQuery.from(20);
            rangeQuery.to(40);
            boolQueryBuilder.must(rangeQuery);
        }

        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort(User.Property.age, SortOrder.DESC);

        Search.Builder builder = new Search.Builder(searchSourceBuilder.toString());
        if (!StringUtils.isEmpty(param.getIndex())) {
            builder.addIndex(param.getIndex());
        } else {
            logger.error("Index不能为空");
            return "Index不能为空！";
        }

        Search search = builder.build();

        SearchResult result = null;
        try {
            result = jestClient.execute(search);
            return result.getJsonString();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("es查询异常 {}", e);
            return result.getErrorMessage();
        }
    }
}
